package com.xpec.c4.service.utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 使用java.util.zip的自带压缩与解压缩
 * 
 * @author Bany
 * 
 * @since 2009-1-2 下午03:27:46
 * 
 */

public class JavaZip {

	//private static final int CACHE_SIZE = 4096;
	private static ThreadLocal<Inflater> decompressers = new ThreadLocal<Inflater>();
	private static ThreadLocal<Deflater> compressers = new ThreadLocal<Deflater>();
	
	public static ByteBuffer compress(ByteBuffer buffer){
		byte[] input=new byte[buffer.remaining()];
		buffer.get(input);
		byte[] output=compressBytes(input);
		ByteBuffer outByteBuffer=ByteBuffer.allocate(output.length);
		outByteBuffer.put(output);
		outByteBuffer.flip();
		return outByteBuffer;
	}
	
	public static byte[] compress(byte[] input){
		byte[] output=compressBytes(input);
		return output;
	}
	
	public static ByteBuffer decompress(ByteBuffer buffer){
		byte[] input=new byte[buffer.remaining()];
		buffer.get(input);
		byte[] output=decompressBytes(input);
		ByteBuffer outByteBuffer=ByteBuffer.allocate(output.length);
		outByteBuffer.put(output);
		outByteBuffer.flip();
		return outByteBuffer;
	}

	public static byte[] compressBytes(byte input[]) {
		Deflater compresser=getCompresser();
		compresser.reset();
		compresser.setInput(input);
		compresser.finish();
		byte output[] = new byte[0];
		ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
		try {
			byte[] buf = new byte[input.length];
			int got;
			while (!compresser.finished()) {
				got = compresser.deflate(buf);
				o.write(buf, 0, got);
			}
			output = o.toByteArray();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output;
	}

	public static byte[] decompressBytes(byte input[]) {
		Inflater decompresser=getDecompresser();
		byte output[] = new byte[0];
		decompresser.reset();
		decompresser.setInput(input);
		ByteArrayOutputStream o = new ByteArrayOutputStream(input.length);
		try {
			byte[] buf = new byte[input.length*2];
			int got;
			while (!decompresser.finished()) {
				got = decompresser.inflate(buf);
				o.write(buf, 0, got);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return output;
	}
	
	private static Deflater getCompresser(){
		Deflater compresser=compressers.get();
		if(compresser==null){
			compresser=new Deflater();
			compressers.set(compresser);
		}
		return compresser;		
	}
	
	private static Inflater getDecompresser(){
		Inflater decompresser=decompressers.get();
		if(decompresser==null){
			decompresser=new Inflater();
			decompressers.set(decompresser);
		}
		return decompresser;		
	}
}
